<template>
  <!-- :on-success="handleAvatarSuccess" -->
  <div>
    <el-upload
      class="avatar-uploader"
      action="#"
      :show-file-list="false"
      :before-upload="beforeAvatarUpload"
      :http-request="upload"
    >
      <el-progress v-if="showProgress" type="circle" :percentage="percent" class="progress" />
      <img v-if="value" :src="value" class="avatar">
      <i v-else class="el-icon-plus avatar-uploader-icon" />
    </el-upload>
  </div>
</template>

<script>
// 下面的代码是固定写法
// const COS = require('cos-js-sdk-v5')
import COS from 'cos-js-sdk-v5'
// 填写自己腾讯云cos中的key和id (密钥)
const cos = new COS({
  SecretId: 'AKID41pRuGyc9XnsLgu6EcKJNByoyZgysX0V', // 身份识别ID
  SecretKey: 'X0lUBeDCSVVO8euzsnZrBPTL0ShrrkU5' // 身份秘钥
})
export default {
  name: 'UploadImg',
  props: {
    value: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      percent: 0,
      showProgress: false
    }
  },
  methods: {
    upload(res) {
      // console.log(file)
      if (res.file) {
        this.showProgress = true
        // 执行上传操作
        cos.putObject({
          Bucket: 'web75-1312368085', /* 存储桶 */
          Region: 'ap-nanjing', /* 存储桶所在地域，必须字段 */
          Key: res.file.name, /* 文件名 */
          StorageClass: 'STANDARD', // 上传模式, 标准模式
          Body: res.file, // 上传文件对象
          onProgress: (progressData) => {
            // console.log(progressData)
            this.percent = Math.ceil((progressData.percent * 100))
          }
        }, (err, data) => {
          console.log(err || data)
          this.showProgress = false
          // 上传成功之后
          if (data.statusCode === 200) {
            this.$emit('input', `https:${data.Location}`)
          }
        })
      }
    },
    // handleAvatarSuccess(res, file) {
    //   this.imageUrl = URL.createObjectURL(file.raw)
    // },
    beforeAvatarUpload(file) {
      const isPNG = file.type.startsWith('image/')
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isPNG) {
        this.$message.error('上传的文件必须是图片格式')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isPNG && isLt2M
    }
  }
}
</script>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.progress {
  position: absolute;
  display: flex;
  top: 50%;
  left: 50%;
  transform: translate(-50%,-50%);
  background: rgba(0, 0, 0, 0.1);
}
</style>
